<template>
  <el-dialog title="确定加工单位" :visible.sync="visible" :center="true" width="82%" :close-on-click-modal="false">
    <el-form :model="toolOrderPlanVO" label-width="80px" size="mini" label-position="left" id="materialtype">
      <el-form-item label="订单编号">
        <el-input style="width: 200px" :disabled="true"
                  v-model="toolOrderPlanVO.sn"
        ></el-input>
      </el-form-item>
      <el-form-item label-width="0">
        <el-table
            :data="toolOrderPlanVO.toolOrderItemPlanVOS" border
            stripe
            style="width: 100%" size="mini">
          <el-table-column label="序号" width="50" type="index"></el-table-column>
          <el-table-column label="产品名称" width="150px" prop="name"></el-table-column>
          <el-table-column label="产品图纸" width="150px" prop="toolAttachments">
            <template slot-scope="scope">
              <el-link v-for="attachment in scope.row.toolAttachmentVOS" :key="attachment.id"
                       :href="attachment.filePath"
                       target="_blank">
                {{ attachment.filePath.split('/').pop() }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="图号" width="100px" prop="drawingNumber"></el-table-column>
          <el-table-column label="数量" width="70px" prop="number"></el-table-column>
          <el-table-column label="交货时间" width="100px" prop="requestDeliveryTime"></el-table-column>
          <el-table-column label="生产方式" width="100px">
            <template slot-scope="scope">
              <!--              <el-input size="mini" v-model.number="scope.row.productionQuantity"
                                      @input="handleInput(scope.row, 'productionQuantity')"></el-input>-->
              <el-select v-model="scope.row.optionsProduction" placeholder="请选择" style="width: 100%">
                <el-option
                    v-for="item in optionsProduction"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="70px">
            <template slot-scope="scope">
              <el-input size="mini" v-model.number="scope.row.quantity"
                        @input="handleInput(scope.row, 'teamworkQuantity')"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="外协单位">
            <template slot-scope="scope">
              <el-select v-model="scope.row.teamworkCompany" placeholder="请选择" style="width: 100%">
                <el-option
                    v-for="item in optionsCompany"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-card shadow="never" style="height: 150px; margin-top: 20px" id="materialcard">
      <div slot="header" class="clearfix">
        <span>审批记录</span>
      </div>
      <div ref="canvas" style="width:auto;height: auto;"></div>
    </el-card>
    <el-card shadow="never" id="historycard">
      <div slot="header" class="clearfix">
        <span>审批意见</span>
      </div>
      <el-timeline style="padding: 0 !important;">
        <el-timeline-item
            v-for="(item, index) in processCommentArray"
            :key="index"
            :timestamp=item.taskName placement="top">
          <div
              style="display: flex; align-items: center; justify-content: space-between; width: 100%;border: 1px solid #ebeef5; padding: 0 10px">
            <h4>{{ item.userId }}&nbsp;:&nbsp;{{ item.message }}</h4>
            <h4>{{ item.time }}</h4>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
    <el-row>
      <el-col :span="24">
        <el-input type="textarea" size="mini" rows="3" placeholder="请填写处理意见"
                  v-model="approvalComment"></el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-button type="primary" size="mini" @click="submit">提 交</el-button>
        <el-button type="warning" size="mini" @click="cancle">取 消</el-button>
      </el-col>
    </el-row>

  </el-dialog>
</template>

<script>
import BpmnModeler from "bpmn-js/lib/Modeler";
import bpmnXML from "@/assets/toolProcess.bpmn20.xml"
import "bpmn-js/dist/assets/diagram-js.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
export default {
  name: "ToolProductionType",
  props: {
    historyData: Object
  },
  data() {
    return {
      toolOrderPlanVO: {
        sn: '',
        toolOrderItemPlanVOS: [{
          id: '',
          orderId: '',
          name: '',
          toolAttachmentVOS: [],
          number: '',
          drawingNumber: '',
          requestDeliveryTime: '',
          optionsProduction: '',
          quantity: '',
          teamworkCompany: ''
        }]
      },
      optionsCompany: [
        {
          value: '合格供方1',
          label: '合格供方1'
        }, {
          value: '合格供方2',
          label: '合格供方2'
        },
        {
          value: '合格供方3',
          label: '合格供方3'
        }
      ],
      optionsProduction: [
        {
          value: '内部',
          label: '内部'
        }, {
          value: '外协',
          label: '外协'
        }
      ],
      fileList: [],
      approvalComment: '',
      bpmnModeler: null,
      processCommentArray: [],
    }
  },
  computed: {
    visible: {
      get() {
        return this.$store.state.isVisible;
      },
      set(value) {
        this.$store.commit('setIsVisible', value);
      }
    },
  },
  watch: {
    visible(newVal) {
      console.log('Visible changed to: ', newVal);
    }
  },
  methods: {
    importXMLPromise(xmlData) {
      return new Promise((resolve, reject) => {
        this.bpmnModeler.importXML(xmlData, (err, warnings) => {
          if (err) {
            reject(err);
          } else {
            resolve(warnings);
          }
        });
      });
    },
    loadBPMN() {
      return this.importXMLPromise(bpmnXML).then(warnings => {
        this.bpmnModeler.get('canvas').zoom('fit-viewport');
        return warnings; // 可以返回 warnings 或其他有用的信息
      }).catch(error => {
        console.error('导入流程失败', error);
        this.$message.error('导入失败，请检查XML格式');
        throw error; // 重新抛出错误，以便可以在外部捕获
      });

    },
    applyColors() {
      const elementRegistry = this.bpmnModeler.get('elementRegistry');
      const modeling = this.bpmnModeler.get('modeling');
      // 定义颜色映射
      const colors = {
        waitingToDo: '#E6A23C',
        highPoint: '#E1F3D8',
        iDo: '#67C23A',
        highLine: '#D8E0D4'
      };
      // 遍历 historyData 并应用颜色
      Object.keys(this.historyData).forEach(key => {
        this.historyData[key].forEach(id => {
          if (id) {
            const element = elementRegistry.get(id);
            if (element) {
              // 判断元素类型，应用不同的样式
              if (element.type === 'bpmn:SequenceFlow') { // 对于连线
                modeling.setColor([element], {
                  stroke: colors[key]
                });
              } else { // 对于用户任务节点
                modeling.setColor([element], {
                  stroke: '#545454', // 边框颜色为黑色
                  fill: colors[key], // 填充颜色
                  color: colors[key] // 文本颜色
                });
              }
            }
          }
        });
      });
    },
    handleInput(row, key) {
      if (row[key] > row.number) {
        this.$message({
          type: "error",
          showClose: true,
          message: `不能大于总数量${this.toolOrderPlanVO.toolOrderItemPlanVOS.number},`
        })
        row[key] = row[key].toString().slice(0, -1); // Optionally revert the last input
      } else if (row[key] < 0) {
        this.$message({type: "error", showClose: true, message: "不能是负数"})
        row[key] = 0; // Optionally revert to 0
      }
    },
    cancle() {
      this.$store.commit("setIsVisible", false)
    },
    submit() {
      const planOrderItemWrapper = {
        planToolOrderItemDTOS: this.toolOrderPlanVO.toolOrderItemPlanVOS.map(item => ({
          id: item.id,
          orderId: item.orderId,
          optionsProduction: item.optionsProduction,
          quantity: item.quantity,
          teamworkCompany: item.teamworkCompany
        })),
        approvalCommentDTO: {
          comment: this.approvalComment
        }
      }
      console.log(JSON.stringify(planOrderItemWrapper, null, 2))
      this.$http.post("/tool/updateProductionPlan/", planOrderItemWrapper).then(response => {
        if (response.data.code == 1) {
          this.$message({
            showClose: true,
            message: '提交成功，下一步：公司领导审核',
            type: 'success'
          });
        } else {
          this.$message({
            showClose: true,
            message: '出现错误，请联系管理员',
            type: 'error'
          });
        }
      })
      this.$store.commit("setIsVisible", false)
    }

  },
  mounted() {
    this.$nextTick(() => {
      if (this.$refs.canvas) {
        this.bpmnModeler = new BpmnModeler({
          container: this.$refs.canvas,
          additionalModules: [{
            // 禁用滚轮滚动
            zoomScroll: ["value", ""],
            // 禁止拖动线
            bendpoints: ["value", ""],
            // 禁用左侧面板
            paletteProvider: ["value", ""],
            // 禁止点击节点出现contextPad
            contextPadProvider: ["value", ""],
            // 禁止双击节点出现label编辑框
            labelEditingProvider: ["value", ""]
          }]
        })
      }
      this.loadBPMN().then(() => {
        this.applyColors()
      })
      /*this.$intro().setOptions({
        steps: [
          {
            element: document.querySelector("#materialtype"),
            title: '搅拌工具模块',
            intro: '<h5 style="font-weight: bold;margin: 5px 0">确定加工单位</h5>' +
                '<ul><li><span style="color: deepskyblue">订单编号</span> </li>' +
                '<li><span style="color: deepskyblue">订单信息</span> </li></ul>',
            position: 'center'
          },
          {
            element: document.querySelector("#materialcard"),
            title: '搅拌工具模块',
            intro: '<h5 style="font-weight: bold;margin: 5px 0">确定加工单位</h5>' +
                '<ul><li><span style="color: deepskyblue">历史审批节点</span> 可以查看当前自己所处的流程位置，快速掌握业务流程，并了解整体进度</span> </li></ul>',
            position: 'center'
          },
          {
            element: document.querySelector("#historycard"),
            title: '搅拌工具模块',
            intro: '<h5 style="font-weight: bold;margin: 5px 0">确定加工单位</h5>' +
                '<ul><li><span style="color: deepskyblue">审批意见</span> 有助于提高流程内部的沟通和协作 </li></ul>',
            position: 'center'
          }
        ]
      }).start()*/
    })
    const taskId = this.$store.state.taskId
    this.$http.get(`/tool/showOrderPlanVO/${taskId}`).then(response => {
      if (response.data.code == 1) {
        this.toolOrderPlanVO = response.data.data
        console.log("获取订单信息成功")
      } else {
        console.log("失败")
      }
    })
    this.$http.get(`/history/comment/${taskId}`).then((response) => {
      if (response.data.code == 1) {
        this.processCommentArray = response.data.data
      }
    })
  },

}
</script>

<style scoped>
::v-deep .el-card__header {
  padding: 5px 10px !important;
}
</style>